<template>
  <div class="app-container" :class="{ 'dark-mode': appStore.isDarkMode }">
    <!-- 侧边栏 -->
    <aside class="sidebar agri-sidebar" :class="{ 'collapsed': appStore.sidebarCollapsed }">
      <div class="sidebar-header">
        <img src="../assets/logo.png" alt="智慧农业" class="logo" v-if="!appStore.sidebarCollapsed" />
        <img src="../assets/logo-small.png" alt="智慧农业" class="logo-small" v-else />
        <h1 class="system-title" v-if="!appStore.sidebarCollapsed">智慧农业系统</h1>
      </div>
      
      <div class="sidebar-content">
        <el-menu
          :collapse="appStore.sidebarCollapsed"
          :default-active="activeMenu"
          router
          class="sidebar-menu agri-menu"
          :collapse-transition="false"
          :unique-opened="true"
        >
          <!-- 仪表盘 -->
          <el-menu-item index="/main/dashboard">
            <el-icon><TrendCharts /></el-icon>
            <template #title>仪表盘</template>
          </el-menu-item>
          
          <!-- 农户菜单 -->
          <el-sub-menu index="/main/farmer" v-if="userStore.isFarmer">
            <template #title>
              <el-icon><Management /></el-icon>
              <span>农户管理</span>
            </template>
            <el-menu-item index="/main/farmer/land">
              <el-icon><Location /></el-icon>
              <span>土地管理</span>
            </el-menu-item>
            <el-menu-item index="/main/farmer/planting">
              <el-icon><Crop /></el-icon>
              <span>种植管理</span>
            </el-menu-item>
            <el-menu-item index="/main/farmer/fertilizer">
              <el-icon><SetUp /></el-icon>
              <span>施肥管理</span>
            </el-menu-item>
            <el-menu-item index="/main/farmer/inventory">
              <el-icon><House /></el-icon>
              <span>库存管理</span>
            </el-menu-item>
            <el-menu-item index="/main/farmer/trade">
              <el-icon><Shop /></el-icon>
              <span>交易中心</span>
            </el-menu-item>
          </el-sub-menu>
          
          <!-- 农产品买家菜单 -->
          <el-sub-menu index="/main/buyer" v-if="userStore.isBuyer">
            <template #title>
              <el-icon><ShoppingCart /></el-icon>
              <span>买家管理</span>
            </template>
            <el-menu-item index="/main/buyer/orders">
              <el-icon><List /></el-icon>
              <span>订单管理</span>
            </el-menu-item>
            <el-menu-item index="/main/buyer/farmers">
              <el-icon><User /></el-icon>
              <span>农户浏览</span>
            </el-menu-item>
            <el-menu-item index="/main/buyer/complaints">
              <el-icon><Warning /></el-icon>
              <span>投诉管理</span>
            </el-menu-item>
          </el-sub-menu>
          
          <!-- 肥料卖家菜单 -->
          <el-sub-menu index="/main/seller" v-if="userStore.isSeller">
            <template #title>
              <el-icon><Goods /></el-icon>
              <span>卖家管理</span>
            </template>
            <el-menu-item index="/main/seller/products">
              <el-icon><Box /></el-icon>
              <span>商品管理</span>
            </el-menu-item>
            <el-menu-item index="/main/seller/seller-orders">
              <el-icon><Document /></el-icon>
              <span>订单处理</span>
            </el-menu-item>
          </el-sub-menu>
          
          <!-- 通用菜单 -->
          <el-menu-item index="/main/messages">
            <el-icon><Message /></el-icon>
            <template #title>消息中心</template>
          </el-menu-item>
          
          <el-menu-item index="/main/profile">
            <el-icon><User /></el-icon>
            <template #title>个人中心</template>
          </el-menu-item>
        </el-menu>
      </div>
      
      <div class="sidebar-footer">
        <el-tooltip 
          :content="appStore.sidebarCollapsed ? '展开菜单' : '折叠菜单'" 
          placement="right"
        >
          <el-button 
            @click="appStore.toggleSidebar" 
            circle 
            plain
            class="agri-icon-button"
          >
            <el-icon>
              <component :is="appStore.sidebarCollapsed ? Expand : Fold" />
            </el-icon>
          </el-button>
        </el-tooltip>
        
       
      </div>
    </aside>
    
    <!-- 主内容区域 -->
    <div class="main-container">
      <!-- 顶部导航 -->
      <header class="header agri-header">
        <div class="header-left">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item v-for="(item, index) in appStore.currentBreadcrumb" :key="index">
              {{ item.title }}
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        
        <div class="header-right">
          <!-- 通知图标 - 使用前端模拟通知 -->
          <el-dropdown trigger="click" @command="handleCommand">
            <el-badge :value="appStore.unreadNotificationsCount" :hidden="!appStore.hasUnreadNotifications">
              <el-button circle plain class="agri-icon-button">
                <el-icon><Bell /></el-icon>
              </el-button>
            </el-badge>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="markAllRead" v-if="appStore.hasUnreadNotifications">
                  标记全部已读
                </el-dropdown-item>
                <el-dropdown-item command="viewAll">
                  查看所有通知
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          
          <!-- 用户头像下拉菜单 -->
          <el-dropdown trigger="click" @command="handleCommand">
            <div class="user-profile">
              <el-avatar :size="32" src="/avatar.png" />
              <span class="username">{{ userInfo.name }}</span>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">个人中心</el-dropdown-item>
                <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </header>
      
      <!-- 内容区域 -->
      <main class="content">
        <router-view v-slot="{ Component }">
          <transition name="fade-transform" mode="out-in">
            <keep-alive>
              <component :is="Component" />
            </keep-alive>
          </transition>
        </router-view>
      </main>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useUserStore, useAppStore } from '../store';
import {
  Document,
  Menu,
  Location,
  Setting,
  User,
  ShoppingCart,
  Box,
  Goods,
  PieChart,
  List,
  Message,
  Warning,
  TrendCharts,
  House,
  Shop,
  Bell,
  Expand,
  Fold,
  Sunny,
  Moon,
  Management,
  Crop,
  SetUp
} from '@element-plus/icons-vue';

// 状态管理
const userStore = useUserStore();
const appStore = useAppStore();
const route = useRoute();
const router = useRouter();
const loading = ref(false);

// 计算属性
const activeMenu = computed(() => route.path);
const userInfo = computed(() => userStore.userInfo);

// 处理下拉菜单命令
function handleCommand(command) {
  switch (command) {
    case 'profile':
      router.push('/main/profile');
      break;
    case 'settings':
      router.push('/main/profile?tab=settings');
      break;
    case 'logout':
      handleLogout();
      break;
    case 'markAllRead':
      appStore.markAllNotificationsAsRead();
      break;
    case 'viewAll':
      router.push('/main/messages');
      break;
  }
}

// 处理退出登录
async function handleLogout() {
  try {
    await userStore.logoutUser();
    router.push('/auth/login');
  } catch (error) {
    console.error('退出登录失败', error);
  }
}

// 组件挂载后
onMounted(async () => {
  if (!userStore.isLoggedIn) {
    router.push('/auth/login');
    return;
  }
  
  // 设置页面标题
  document.title = `智慧农业信息系统 | ${route.meta.title || '首页'}`;
  
  // 根据路由设置面包屑
  setBreadcrumb();
  
  // 从后端获取通知数据
  loading.value = true;
  try {
    console.log('正在从后端获取通知数据');
    // 添加一个小延迟，确保登录流程已完成
    setTimeout(async () => {
      try {
        await appStore.fetchNotifications();
        await appStore.fetchUnreadCount();
      } catch (error) {
        console.error('加载通知失败', error);
        // 错误处理，不显示给用户
      } finally {
        loading.value = false;
      }
    }, 1000); // 延迟1秒后获取通知
  } catch (error) {
    console.error('加载通知初始化失败', error);
    loading.value = false;
  }
});

// 设置面包屑
function setBreadcrumb() {
  const matched = route.matched.filter(item => item.meta && item.meta.title);
  const breadcrumb = matched.map(item => ({
    title: item.meta.title,
    path: item.path
  }));
  
  // 添加首页
  if (breadcrumb.length > 0 && breadcrumb[0].path !== '/main/dashboard') {
    breadcrumb.unshift({
      title: '首页',
      path: '/main/dashboard'
    });
  }
  
  appStore.setBreadcrumb(breadcrumb);
}
</script>

<style scoped>
.app-container {
  height: 100vh;
  display: flex;
  overflow: hidden;
}

.sidebar {
  width: 260px;
  height: 100%;
  display: flex;
  flex-direction: column;
  transition: width 0.3s;
  background-color: var(--el-bg-color);
  border-right: 1px solid var(--el-border-color-light);
}

.agri-sidebar {
  background-color: #f8fbf8;
  border-right: 1px solid #e8f5e9;
}

.dark-mode .agri-sidebar {
  background-color: var(--el-bg-color-darker);
  border-right: 1px solid var(--el-border-color-darker);
}

.sidebar.collapsed {
  width: 64px;
}

.sidebar-header {
  height: 60px;
  display: flex;
  align-items: center;
  padding: 0 16px;
  border-bottom: 1px solid var(--el-border-color-light);
}

.agri-sidebar .sidebar-header {
  border-bottom: 1px solid #e8f5e9;
  background-color: #f1f8e9;
  justify-content: center;
}

.dark-mode .agri-sidebar .sidebar-header {
  border-bottom: 1px solid var(--el-border-color-darker);
  background-color: var(--el-bg-color-darker);
}

.logo {
  height: 40px;
  margin-right: 10px;
}

.logo-small {
  height: 32px;
}

.system-title {
  margin: 0;
  padding: 0;
  font-size: 16px;
  color: #2e7d32;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.dark-mode .system-title {
  color: var(--el-color-primary-light-5);
}

.sidebar-content {
  flex: 1;
  overflow-y: auto;
}

.sidebar-menu {
  border-right: none;
}

.agri-menu.el-menu {
  background-color: #f8fbf8;
}

.dark-mode .agri-menu.el-menu {
  background-color: var(--el-bg-color-darker);
}

.agri-menu.el-menu .el-menu-item.is-active {
  background-color: #e8f5e9;
  color: #2e7d32;
}

.dark-mode .agri-menu.el-menu .el-menu-item.is-active {
  background-color: var(--el-color-primary-dark-2);
  color: var(--el-color-white);
}

.sidebar-footer {
  padding: 16px;
  display: flex;
  align-items: center;
  justify-content: space-around;
  border-top: 1px solid var(--el-border-color-light);
}

.agri-sidebar .sidebar-footer {
  border-top: 1px solid #e8f5e9;
  background-color: #f1f8e9;
}

.dark-mode .agri-sidebar .sidebar-footer {
  border-top: 1px solid var(--el-border-color-darker);
  background-color: var(--el-bg-color-darker);
}

.main-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.header {
  height: 60px;
  padding: 0 20px;
  border-bottom: 1px solid var(--el-border-color-light);
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: var(--el-bg-color);
}

.agri-header {
  background: linear-gradient(to right, #f1f8e9, #f8fbf8);
  border-bottom: 1px solid #e8f5e9;
}

.dark-mode .agri-header {
  background: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color-darker);
}

.agri-icon-button {
  color: #4caf50;
  border-color: #c8e6c9;
}

.dark-mode .agri-icon-button {
  color: var(--el-color-primary-light-3);
  border-color: var(--el-color-primary-light-1);
}

.header-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.user-profile {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.username {
  margin-left: 8px;
  font-weight: bold;
  display: inline-block;
  color: #2e7d32;
}

.dark-mode .username {
  color: var(--el-color-primary-light-5);
}

.content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

/* 过渡动画 */
.fade-transform-enter-active,
.fade-transform-leave-active {
  transition: all 0.3s;
}

.fade-transform-enter-from {
  opacity: 0;
  transform: translateY(20px);
}

.fade-transform-leave-to {
  opacity: 0;
  transform: translateY(-20px);
}

/* 响应式布局 */
@media (max-width: 768px) {
  .sidebar {
    position: fixed;
    z-index: 1001;
  }
  
  .sidebar:not(.collapsed) {
    transform: translateX(0);
  }
  
  .sidebar.collapsed {
    transform: translateX(-100%);
  }
}
</style> 